package com.zhaocaimao.xiaohashu.auth.sms;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.protobuf.ServiceException;
import com.zhaocaimao.framework.common.exception.BizException;
import com.zhaocaimao.framework.common.util.JsonUtils;
import com.zhaocaimao.xiaohashu.auth.enums.ResponseCodeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.manager.HTMLManagerServlet;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
/**
 * 短信发送工具类
 * @author: zhaobin
 * @date: 2025-09-11 15:11:46
 */
public class AliyunSmsHelper {


    @Resource
    private Client client;


    /**
     * 发送短信
     * @param signName
     * @param templateCode
     * @param phone
     * @param templateParam
     * @return
     */
    public boolean sendMessage(String signName, String templateCode, String phone, String templateParam) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam(templateParam);
        RuntimeOptions runtime = new RuntimeOptions();

        try {
            log.info("==> 开始短信发送, phone: {}, signName: {}, templateCode: {}, templateParam: {}", phone, signName, templateCode, templateParam);

            // 发送短信
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);

            log.info("==> 短信发送成功, response: {}", JsonUtils.toJsonString(response));
            return true;
        } catch (Exception error) {
            log.error("==> 短信发送错误: ", error);
            return false;
        }
    }

    /**
     * 三网短信发送
     * @author: zhaobin
     * @date: 2025-09-11 15:53:06
     */
    public void send(String templateId,String phone,String templateParam){
        String host = "https://jumsendv2.market.alicloudapi.com";
        String path = "/sms/send-v2";
        String method = "POST";
        String appcode = "bdd48da3562e41739557026b2ddb9da5";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();

        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("mobile", phone);
        bodys.put("templateId", templateId);
        bodys.put("value", templateParam);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            //获取response的body
            String data = EntityUtils.toString(response.getEntity());

            HashMap<String, String> resultMap = JSONObject.parseObject(data, HashMap.class);
            String msg = resultMap.get("msg");

            if(!"成功".equals(msg)){
                log.error("短信发送失败：msg = " + msg);
                throw new ServiceException("短信发送失败");
            }
            log.info("==> 短信发送成功, response: {}", data);

        } catch (Exception e) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_ERROR);
        }
    }

}
